package components.managers
{
    import components.core.UIComponent;
    
    import flash.display.DisplayObject;
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    public class DragManager
    {

        private static var _dragVO:DragVO;

        private static var _currentDropTarget:UIComponent;

        public function DragManager()
        {
        }

        public static function startDrag(dragVO:DragVO):void
        {
            if (SystemManager.rootStage == null)
                return;

            stopDrag();

            _dragVO = dragVO;

            var dragSp:Sprite = _dragVO.sp;
            SystemManager.rootStage.addChild(dragSp);

            dragSp.startDrag();
			SystemManager.rootStage.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler, false, 0, true);

            SystemManager.rootStage.addEventListener(MouseEvent.MOUSE_UP, stopDragHandler, false, 0, true);
        }

        protected static function stopDragHandler(event:MouseEvent):void
        {
            stopDrag(true);
        }

        public static function stopDrag(drop:Boolean=false):void
        {
            if (_dragVO)
            {
                SystemManager.rootStage.removeEventListener(MouseEvent.MOUSE_UP, stopDragHandler);
				SystemManager.rootStage.removeEventListener(MouseEvent.MOUSE_MOVE, moveHandler);

                var dragSp:Sprite = _dragVO.sp;
                dragSp.stopDrag();

                SystemManager.rootStage.removeChild(dragSp);

				if(_currentDropTarget)
				{
					if(drop)
						_currentDropTarget.dragDrop(_dragVO);
					_currentDropTarget=null;
				}
				
                _dragVO = null;
            }
        }

        protected static function moveHandler(event:MouseEvent):void
        {
            var dropTarget:DisplayObject = _dragVO.sp.dropTarget;
            var ui:UIComponent = getDropTargetUI(dropTarget);
			if(ui)
				ui=ui.dropTargetComp;
			
			if(ui==null && _currentDropTarget && _currentDropTarget.isStageMouseIn)
			{
				return ;
			}
			
            if (ui)
            {
				if(ui.dropEnater && ui != _currentDropTarget)
				{
					if(_currentDropTarget)
					{
		                _currentDropTarget.dragExit(_dragVO);
		                _currentDropTarget = null;
					}
					
					_currentDropTarget = ui;
					ui.dragEnter(_dragVO);
				}
				else if(_currentDropTarget && !_currentDropTarget.isStageMouseIn)
				{
					_currentDropTarget.dragExit(_dragVO);
					_currentDropTarget = null;
				}
            }
        }

        protected static function getDropTargetUI(display:DisplayObject):UIComponent
        {
            while (display && display!=SystemManager.rootStage && !(display is UIComponent))
            {
				display = display.parent;
            }

            return display as UIComponent;
        }
    }
}